import type { SentLoginInfo } from "../models/Login";
import { autoLoginAPI, loginAPI } from "../apis/LoginAPI";
import store from "../store";

export const loginUser = async (email: string, password: string) => {
    console.log(`用户登录:${email}...`)
    //封装查询条件 
    const loginInfo: SentLoginInfo = {
        email: email,
        password: password
    };
    const result = await loginAPI(loginInfo);
    if (result.code !== 0) {
        console.log(result.message)
    }
    if (result.code === 0 && result.data !== null) {
        console.log('登录成功')
        localStorage.setItem('token', result.data.token)
        result.data.token = ''
        localStorage.setItem('userInfo', JSON.stringify(result.data))
        store.dispatch('loadUserInfoFromLocalStorage')
        return
    }
    return result.code
}


export async function autoLogin(token: string | null) {
     if (token) {
         const result = await autoLoginAPI(token)
         if (result.code === 0 && result.data !== null) {
             console.log('自动登录成功')
             localStorage.setItem('token', result.data.token)
             result.data.token = ''
             localStorage.setItem('userInfo', JSON.stringify(result.data))
             store.dispatch('loadUserInfoFromLocalStorage')
             return
         } else {
             console.log('自动登录失败2')
         }
     } else {
        console.log('自动登录失败1')
     }
}